package com.qfedu.controller;

import com.qfedu.bean.Book;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author:zhengyilong
 * @email:1797344574@qq.com
 * @phone:13479394730
 * @desc:
 * @DateTime:2022/5/10 22:12
 **/
@Controller
@RequestMapping("/book")
public class BookController {

    @RequestMapping("/add")
    public String addBook(Book book, MultipartFile imgFile, HttpServletRequest request) throws IOException {
        System.out.println("---------------add");
        System.out.println(book);
        //imgFile就表示上传的图片
        //1、截取上传文件的后缀名，生成新的文件名
        String originalFilename = imgFile.getOriginalFilename();
        //.lastIndexOf 获取到字符的下标    .substring 截取从参数位为往后字符串
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));//.jpg
        String fileName = System.currentTimeMillis()+ext;

        //2、获取imgs目录在服务器的路径
        String dir = request.getServletContext().getRealPath("imgs");
        String savePath = dir+"/"+fileName;
        //或者也可以保存在自定义目录下
        String path = "D:\\MyMaven\\springmvc-demo2\\src\\main\\webapp\\imgs\\"+fileName;

        //3、保存文件
        imgFile.transferTo(new File(savePath));

        //4、将图片的访问路径设置到book对象
        book.setBookImg("imgs/"+fileName);

        //5、调用service保存book保存数据库
        //略

        return "/tips.jsp";
    }

    @RequestMapping("/list")
    @ResponseBody
    public String[] listImgs(HttpServletRequest request){
        //1、从img目录下获取所有的图片信息
        String dir = request.getServletContext().getRealPath("imgs");
        File imgDir = new File(dir);
        String[] fileNames = imgDir.list();
        return fileNames;
    }

    @RequestMapping("/download")
    public void downloadImg(String fname,HttpServletRequest request, HttpServletResponse response) throws Exception {
        //从imgs目录找到当前文件
        String dir = request.getServletContext().getRealPath("imgs");
        String filePath = dir + "/" + fname;
        FileInputStream fileInputStream = new FileInputStream(filePath);

        //设置一个浏览器无法识别的类型，不然浏览器接收到图片会直接打开而不是下载
        response.setContentType("application/exe");
        //设置响应头，在响应头中将文件名写入，使得浏览器能正确下载
        response.addHeader("Content-Disposition","attachment;filename="+fname);

        IOUtils.copy(fileInputStream,response.getOutputStream());
    }

    @RequestMapping("/query")
    public String query(String bookId){
        int bid = Integer.parseInt(bookId);
        return "/tips.jsp";
    }
}

